#include "ntpTime.h"
#include <time.h>

NTPTime::NTPTime() {
    _lastUpdate = 0;
    _hour = 0;
    _minute = 0;
    _second = 0;
    _timeValid = false;
    _timezoneOffset = 8;  // 默认北京时间（UTC+8）
}

bool NTPTime::begin() {
    configTime(_timezoneOffset * 3600, 0, "pool.ntp.org", "time.nist.gov");
    return true;
}

bool NTPTime::attemptSyncIfNeeded(unsigned long &lastNTPAttempt, unsigned long intervalMs) {
    if (millis() - lastNTPAttempt < intervalMs) return false; // not time yet
    lastNTPAttempt = millis();
    return updateTime();
}

bool NTPTime::updateTime() {
    struct tm timeinfo;
    if (!getLocalTime(&timeinfo, 10000)) {  // 10秒超时
    Serial.println("Failed to get NTP time");
        _timeValid = false;
        return false;
    }

    _hour = timeinfo.tm_hour;
    _minute = timeinfo.tm_min;
    _second = timeinfo.tm_sec;
    _lastUpdate = millis();
    _timeValid = true;

    Serial.printf("NTP time updated: %02d:%02d:%02d\n", _hour, _minute, _second);
    return true;
}

uint8_t NTPTime::getHour() {
    if (_timeValid) {
        // 基于最后一次同步时间计算当前时间
        unsigned long elapsedSeconds = (millis() - _lastUpdate) / 1000;
        unsigned long totalSeconds = _hour * 3600 + _minute * 60 + _second + elapsedSeconds;
        return (totalSeconds / 3600) % 24;
    }
    return 0;
}

uint8_t NTPTime::getMinute() {
    if (_timeValid) {
        unsigned long elapsedSeconds = (millis() - _lastUpdate) / 1000;
        unsigned long totalSeconds = _hour * 3600 + _minute * 60 + _second + elapsedSeconds;
        return (totalSeconds / 60) % 60;
    }
    return 0;
}

uint8_t NTPTime::getSecond() {
    if (_timeValid) {
        unsigned long elapsedSeconds = (millis() - _lastUpdate) / 1000;
        unsigned long totalSeconds = _hour * 3600 + _minute * 60 + _second + elapsedSeconds;
        return totalSeconds % 60;
    }
    return 0;
}

String NTPTime::getFormattedTime() {
    if (!_timeValid) {
        return "Time not synced";
    }

    uint8_t hour = getHour();
    uint8_t minute = getMinute();
    uint8_t second = getSecond();

    char buffer[20];
    snprintf(buffer, sizeof(buffer), "%02d:%02d:%02d", hour, minute, second);
    return String(buffer);
}

bool NTPTime::isTimeValid() {
    return _timeValid;
}

void NTPTime::setTimezone(int offset) {
    _timezoneOffset = offset;
    // 重新配置时区
    if (WiFi.status() == WL_CONNECTED) {
        configTime(_timezoneOffset * 3600, 0, "pool.ntp.org", "time.nist.gov");
    }
}